package com.wyix.pool;

import java.util.concurrent.*;

public class AbortPolicyDemo {
    public static void main(String[] args) {
        // 自定义线程池（有界队列，触发AbortPolicy）
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                2,               // corePoolSize：核心线程数2
                4,               // maxPoolSize：最大线程数4
                30,              // keepAliveTime：空闲线程存活30秒
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),  // 有界队列，容量5
                new ThreadPoolExecutor.AbortPolicy()  // 显式设置拒绝策略
        );

        // 提交10个任务（超过 4线程+5队列=9的负载）
        for (int i = 0; i < 10; i++) {
            int taskId = i + 1;
            try {
                threadPool.execute(() -> {
                    System.out.println("任务" + taskId + " 执行中...");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                });
                System.out.println("任务" + taskId + " 加入队列");
            } catch (RejectedExecutionException e) {
                System.out.println("任务" + taskId + " 被拒绝！原因：" + e.getMessage());
            }
        }

        threadPool.shutdown();
    }
}